<template>
  <div class="company-user-list" v-show="isShow">
    <ul class="global-operation-list">
      <li class="global-operation-left">
        <ul class="global-filter-list">
          <li class="global-filter-item">
            <h2 class="global-filter-item-title">关键字：</h2>
            <el-input placeholder="请输入商务名字或者手机号" v-model="searchForm.keyword" @change="getPost" style="width: 250px"
              clearable></el-input>
          </li>
          <li class="global-filter-item">
            <h2 class="global-filter-item-title">职称：</h2>
            <el-select v-model="searchForm.gradeId" placeholder="请选择" clearable>
              <el-option v-for="(item,index) in gradeList" :key="index" :label="item.sysValueName"
                :value="item.id"></el-option>
            </el-select>
          </li>
          <li class="global-filter-item">
            <h2 class="global-filter-item-title">区域：</h2>
            <el-select v-model="searchForm.area" placeholder="请选择" clearable
              @change="(val) => changeAreaList(val, 'searchGroupList')">
              <el-option v-for="(item,index) in areaList" :key="index" :label="item.sysValueName"
                :value="item.id"></el-option>
            </el-select>
          </li>
          <li class="global-filter-item">
            <h2 class="global-filter-item-title">分组：</h2>
            <el-select v-model="searchForm.groupId" placeholder="请选择" clearable>
              <el-option v-for="(item,index) in searchGroupList" :key="index" :label="item.sysValueName"
                :value="item.id"></el-option>
            </el-select>
          </li>
          <li class="global-filter-item">
            <h2 class="global-filter-item-title">状态：</h2>
            <el-select v-model="searchForm.status" placeholder="请选择" clearable>
              <el-option v-for="(item,index) in statusList" :key="index" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </li>
          <li class="global-filter-item">
            <h2 class="global-filter-item-title">商务类型：</h2>
            <el-select v-model="searchForm.businessType" placeholder="请选择" clearable>
              <el-option v-for="(item,index) in businessTypeList" :key="index" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </li>
          <li class="global-filter-item">
            <h2 class="global-filter-item-title">部门：</h2>
            <el-select v-model="searchForm.departId" placeholder="请选择" clearable>
              <el-option v-for="(item,index) in departList" :key="index" :label="item.sysValueName"
                :value="item.id"></el-option>
            </el-select>
          </li>
          <li class="global-filter-item">
            <h2 class="global-filter-item-title">月份：</h2>
            <el-date-picker v-model="searchForm.chooseShowMonth" type="monthrange" range-separator="至"
              start-placeholder="开始月份" end-placeholder="结束月份">
            </el-date-picker>
          </li>

          <li class="global-filter-item">
            <el-button type="primary" class="global-filter-item-search" @click="rePosts">搜索</el-button>
          </li>
          <li class="global-filter-item">
            <el-button type="primary" class="global-filter-item-search" v-if="operationList.includes('add')"
              @click="add">添加
            </el-button>
          </li>
        </ul>
      </li>
    </ul>
    <div class="global-table-content">
      <div class="global-table-content-a">
        <el-table :data="dataList" style="width: 100%" :row-style="{height: '0'}" :cell-style="{padding: '3px'}"
          height="620" border v-loading="tableLoading">
          <el-table-column prop="username" label="商务名字" show-overflow-tooltip width="150px">
          </el-table-column>
          <el-table-column prop="telephone" label="手机号" show-overflow-tooltip width="150px">
          </el-table-column>
          <el-table-column prop="nowMonthBasicSalary" label="当月底薪" show-overflow-tooltip width="150px">
          </el-table-column>
          <el-table-column prop="nowMonthPerformanceGoodsValue" label="当月绩效货值" show-overflow-tooltip width="150px">
          </el-table-column>
          <el-table-column prop="gradeName" label="职称" show-overflow-tooltip width="150px">
          </el-table-column>
          <el-table-column prop="area" label="区域" show-overflow-tooltip width="150px">
          </el-table-column>
          <el-table-column prop="groupName" label="分组" show-overflow-tooltip width="150px">
          </el-table-column>
          <el-table-column prop="teamType" label="组内职务" show-overflow-tooltip width="150px">
            <template slot-scope="scope">
              {{
              scope.row.teamType ? (scope.row.teamType == 1 ? '组长' : scope.row.teamType == 2 ? '组员' : '--') : '-'
              }}
            </template>
          </el-table-column>
          <el-table-column v-for="(item,index) in monthList" :key="index" :prop="item.month" :label="item.month">
            <el-table-column prop="monthBasicSalary" label="当月底薪" show-overflow-tooltip width="80px">
              <template slot-scope="scope">
                {{ scope.row.monthList && scope.row.monthList[item.month] ?
                JSON.parse(JSON.stringify(scope.row.monthList[item.month])).monthBasicSalary : '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="monthPerformanceGoodsValue" label="当月绩效货值" show-overflow-tooltip width="80px">
              <template slot-scope="scope">
                {{ scope.row.monthList && scope.row.monthList[item.month] ?
                JSON.parse(JSON.stringify(scope.row.monthList[item.month])).monthPerformanceGoodsValue : '-' }}
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column prop="businessType" label="商务类型" show-overflow-tooltip width="150px">
            <template slot-scope="scope">
              {{ scope.row.businessType ? (scope.row.businessType == 1 ? 'KA' : 'BD') : '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="departName" label="部门" show-overflow-tooltip width="150px">
          </el-table-column>
          <el-table-column prop="totalGrossProfit" label="总毛利润" show-overflow-tooltip width="150px">
            <template slot-scope="scope">
              {{ scope.row.totalGrossProfit ? scope.row.totalGrossProfit : '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="joinDate" label="加入时间" show-overflow-tooltip width="150px">
          </el-table-column>
          <el-table-column prop="createDate" label="创建时间" show-overflow-tooltip width="150px">
          </el-table-column>
          <el-table-column prop="status" label="状态" show-overflow-tooltip width="150px">
            <template slot-scope="scope">
              {{ scope.row.status ? (scope.row.status == 1 ? '可用' : scope.row.status == 2 ? '已辞职(编外)' : '--') : '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="departTime" label="离职时间" show-overflow-tooltip width="150px">
            <template slot-scope="scope">
              {{ scope.row.departTime ? scope.row.departTime : '-' }}
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="100">
            <template slot-scope="scope">
              <el-dropdown @command="handleCommand($event, scope.row)">
                <span class="el-dropdown-link"
                  :style="{color: $store.state.theme.theme_color || '#03C192', cursor: 'pointer'}">
                  操作
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="handleViewClick" v-if="operationList.includes('businessData:view')">
                    查看跟进记录
                  </el-dropdown-item>
                  <el-dropdown-item command="handleClick" v-if="operationList.includes('edit')">编辑</el-dropdown-item>
                  <el-dropdown-item command="handleClickResetPassword" v-if="operationList.includes('resetPassword')">
                    重置密码
                  </el-dropdown-item>
                  <el-dropdown-item command="handleClickResignation" v-if="operationList.includes('editStatus')">辞职
                  </el-dropdown-item>
                  <el-dropdown-item command="handleClickDel" v-if="operationList.includes('delStatus')">删除
                  </el-dropdown-item>
                  <el-dropdown-item command="handlePerformance" v-if="operationList.includes('selectPerformance')">查看绩效
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>

            </template>
          </el-table-column>
        </el-table>
        <div class="global-page">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="pageSizes"
            :page-size="pageSize" :current-page="pageNum" background layout="sizes, total, prev, pager, next"
            :total="total">
          </el-pagination>
        </div>
      </div>
    </div>

    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" width="70%">
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <el-form-item label="商务名字" prop="username" :label-width="formLabelWidth">
          <el-input v-model="form.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="telephone" :label-width="formLabelWidth">
          <el-input v-model="form.telephone" autocomplete="off"></el-input>
        </el-form-item>
        <!-- <el-form-item label="项目经理" prop="businessAssistantId" :label-width="formLabelWidth">
          <el-select v-model="form.businessAssistantId" placeholder="请选择项目经理">
            <el-option v-for="(item, index) in businessAssistantList" :key="index" :label="item.username"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选品人" prop="productSelectionUserIds" :label-width="formLabelWidth">
          <el-select @change="changeSelectionAssistantUser" v-model="form.productSelectionUserIds" placeholder="请选择选品人"
            clearable>
            <el-option v-for="(item, index) in productSelectionUserList" :key="index" :label="item.nickName"
              :value="item.userId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选品助理" prop="productSelectionAssistantUserIds" :label-width="formLabelWidth">
          <el-select v-model="form.productSelectionAssistantUserIds" placeholder="请选择选品助理" clearable>
            <el-option v-for="(item, index) in productSelectionAssistantUserList" :key="index" :label="item.nickName"
              :value="item.userId"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="默认底薪" prop="basicSalary" :label-width="formLabelWidth">
          <el-input v-model="form.basicSalary" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="默认绩效货值" prop="performanceGoodsValue" :label-width="formLabelWidth">
          <el-input v-model="form.performanceGoodsValue" autocomplete="off" type="number"></el-input>
        </el-form-item>
        <el-form-item label="绩效时间" prop="performanceTime" :label-width="formLabelWidth">
          <el-date-picker type="months" value-format="timestamp" v-model="form.performanceTime" placeholder="选择一个或多个月">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="绩效" prop="performanceTime" :label-width="formLabelWidth"
          v-if="performanceTimeList && performanceTimeList.length > 0">
          <div style="display: -webkit-inline-box;">
            <div>批量修改：</div>
            <div style="display: inline-flex;">
              <div style="display: inline-flex;">
                <el-input v-model="inputPerformancePrice" placeholder="请输入批量修改的绩效"
                  @change="inputChangePerformancePrice">
                </el-input>
                <el-button icon="el-icon-search" @click="inputChangePerformancePriceCommit">提交</el-button>
              </div>
              <div style="margin-left: 10px;display: inline-flex">
                <el-input v-model="inputPerformanceBasicSalary" placeholder="请输入批量修改的底薪"
                  @change="inputChangePerformanceBasicSalary">
                </el-input>
                <el-button icon="el-icon-search" @click="inputChangePerformanceBasicSalaryCommit">提交</el-button>
              </div>
            </div>
          </div>
          <div style="max-height: 400px; overflow-x: auto; margin: 10px 0;">
            <el-form-item v-for="(timeItem, timeIndex) in performanceTimeList" :key="timeIndex"
              :label="formatterTimeYYYYMM(timeItem.time)" style="margin-bottom: 10px;">
              <div style="display: -webkit-inline-box;">
                <div style="display: -webkit-inline-box;margin-left: 10px">
                  <div>绩效：</div>
                  <el-input v-model="timeItem.price" type="number" style="width: 200px;">
                    <template slot="append">元</template>
                  </el-input>
                </div>
                <div style="display: -webkit-inline-box;margin-left: 10px">
                  <div>底薪：</div>
                  <el-input v-model="timeItem.basicSalary" type="number" style="width: 200px;">
                    <template slot="append">元</template>
                  </el-input>
                </div>
                <div style="display: -webkit-inline-box;">
                  <el-button type="danger" icon="el-icon-delete" circle style="margin-left: 10px"
                    @click="delPerformanceTime(timeItem, timeIndex)"></el-button>
                </div>
              </div>
            </el-form-item>
          </div>
        </el-form-item>
        <el-form-item label="职称" prop="gradeId" :label-width="formLabelWidth">
          <el-select v-model="form.gradeId" placeholder="请选择">
            <el-option v-for="(item,index) in gradeList" :key="index" :label="item.sysValueName"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="区域" prop="area" :label-width="formLabelWidth">
          <el-select v-model="form.areaId" placeholder="请选择" @change="(val) => changeAreaList(val, 'formGroupList')">
            <el-option v-for="(item,index) in areaList" :key="index" :label="item.sysValueName"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分组" prop="groupId" :label-width="formLabelWidth">
          <el-select v-model="form.groupId" placeholder="请选择">
            <el-option v-for="(item,index) in formGroupList" :key="index" :label="item.sysValueName"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="组内职位" prop="teamType" :label-width="formLabelWidth">
          <el-select v-model="form.teamType" placeholder="请选择">
            <el-option v-for="(item,index) in teamTypeList" :key="index" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商务类型" prop="businessType" :label-width="formLabelWidth">
          <el-select v-model="form.businessType" placeholder="请选择">
            <el-option v-for="(item,index) in businessTypeList" :key="index" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="departId" :label-width="formLabelWidth">
          <el-select v-model="form.departId" placeholder="请选择">
            <el-option v-for="(item,index) in departList" :key="index" :label="item.sysValueName"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="加入时间" prop="joinTime" :label-width="formLabelWidth">
          <el-date-picker v-model="form.joinTime" type="date" placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="密码" prop="password" :label-width="formLabelWidth">
          <el-input v-model="form.password" autocomplete="off" show-password></el-input>
        </el-form-item>
        <el-form-item v-for="(roleItem) in chooseRoleList" :key="roleItem.id" :label="roleItem.roleName"
          :prop="roleItem.customName" :label-width="formLabelWidth">
          <el-select v-model="form.customValue[roleItem.customName]" placeholder="请选择" filterable
            :multiple="roleItem.multipleType == 1">
            <el-option v-for="(item) in chooseRoleMap[roleItem.id]" :key="item.id" :label="item.username"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>



    <el-dialog title="商务绩效" :visible.sync="performanceListDialog">
      <div style="margin-top: -20px;">
        <el-button type="primary" @click="showAddUpdatePerformanceDialogClick">新增修改商务绩效</el-button>
      </div>
      <div>
        <el-table :data="performanceList">
          <el-table-column property="userName" label="商务名称" width="150"></el-table-column>
          <el-table-column property="chooseTime" label="绩效时间" width="200"></el-table-column>
          <el-table-column property="performanceGoodsPrice" label="绩效货值"></el-table-column>
          <el-table-column property="basicSalary" label="底薪"></el-table-column>
        </el-table>
      </div>

      <div class="global-page">
        <el-pagination @size-change="handleSizeChangePer" @current-change="handleCurrentChangePer"
          :page-sizes="perPageSizes" :page-size="perPageSize" :current-page="perPageNum" background
          layout="sizes, total, prev, pager, next" :total="perTotal">
        </el-pagination>
      </div>
    </el-dialog>


    <businessMsg :business-id="openBusinessId" :is-open="openBusinessMsgStatus" @close="closeBusinessMsg"></businessMsg>


    <el-dialog title="设置离职时间" :visible.sync="setDepartTimeDialog" width="30%"
      :before-close="handleCloseDepartTimeDialog">
      <el-date-picker v-model="setDepartTime" type="datetime" placeholder="选择离职时间" value-format="timestamp"
        format="yyyy-MM-dd">
      </el-date-picker>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setDepartTimeDialog = false">取 消</el-button>
        <el-button type="primary" @click="saveSetDepartTime">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="新增修改商务绩效" :visible.sync="showAddUpdatePerformanceDialog" width="70%"
      :before-close="handleShowAddUpdatePerformanceDialog">
      <div>
        <el-form :model="form" ref="ruleForm">
          <el-form-item label="绩效时间" prop="performanceTime" :label-width="formLabelWidth">
            <el-date-picker type="months" value-format="timestamp" v-model="form.performanceTime"
              placeholder="选择一个或多个月">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="绩效" prop="performanceTime" :label-width="formLabelWidth"
            v-if="performanceTimeList && performanceTimeList.length > 0">
            <div style="display: -webkit-inline-box;">
              <div>批量修改：</div>
              <div style="display: inline-flex;">
                <div style="display: inline-flex;">
                  <el-input v-model="inputPerformancePrice" placeholder="请输入批量修改的绩效"
                    @change="inputChangePerformancePrice">
                  </el-input>
                  <el-button icon="el-icon-search" @click="inputChangePerformancePriceCommit">提交</el-button>
                </div>
                <div style="margin-left: 10px;display: inline-flex">
                  <el-input v-model="inputPerformanceBasicSalary" placeholder="请输入批量修改的底薪"
                    @change="inputChangePerformanceBasicSalary">
                  </el-input>
                  <el-button icon="el-icon-search" @click="inputChangePerformanceBasicSalaryCommit">提交</el-button>
                </div>
              </div>
            </div>
            <div style="max-height: 400px; overflow-x: auto; margin: 10px 0;">
              <el-form-item v-for="(timeItem, timeIndex) in performanceTimeList" :key="timeIndex"
                :label="formatterTimeYYYYMM(timeItem.time)" style="margin-bottom: 10px;">
                <div style="display: -webkit-inline-box;">
                  <div style="display: -webkit-inline-box;margin-left: 10px">
                    <div>绩效：</div>
                    <el-input v-model="timeItem.price" type="number" style="width: 200px;">
                      <template slot="append">元</template>
                    </el-input>
                  </div>
                  <div style="display: -webkit-inline-box;margin-left: 10px">
                    <div>底薪：</div>
                    <el-input v-model="timeItem.basicSalary" type="number" style="width: 200px;">
                      <template slot="append">元</template>
                    </el-input>
                  </div>
                  <div style="display: -webkit-inline-box;">
                    <el-button type="danger" icon="el-icon-delete" circle style="margin-left: 10px"
                      @click="delPerformanceTime(timeItem, timeIndex)"></el-button>
                  </div>
                </div>
              </el-form-item>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showAddUpdatePerformanceDialog = false">取 消</el-button>
        <el-button type="primary" @click="saveAddUpdatePerformance">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import API from "@/api/apiBusiness";
import APISysLabel from "@/api/apiSysLabel";
import APIAdmin from "@/api/apiCompanyUser";
import businessMsg from "@/components/BusinessMsg";
import APIUser from "@/api/apiUser";

export default {
  name: "BusinessList",
  components: {
    businessMsg,
  },
  props: {
    operationList: Array,
    isShow: Boolean,
  },
  watch: {
    isShow(val) {
      if (val) {
        this.getPost()
      }
    },
    "form.performanceTime"(val){
      if (Array.isArray(val)){
        if (val && val.length > 0) {
          if (this.performanceTimeList && this.performanceTimeList.length > 0) {
            let hasTimeList = []
            this.performanceTimeList.forEach(item => {
              hasTimeList.push(item.time)
            })
            let finalList = []
            val.forEach(item => {
              if (hasTimeList.includes(item)) {
                this.performanceTimeList.forEach(timeItem => {
                  if (timeItem.time == item) {
                    finalList.push({
                      time: item,
                      price: timeItem.price,
                    })
                  }
                })
              } else {
                finalList.push({
                  time: item,
                  price: null,
                })
              }
            })
            this.performanceTimeList = finalList
          } else {
            val.forEach(item => {
              this.performanceTimeList.push({
                time: item,
                price: null,
              })
            })
          }
        } else {
          this.performanceTimeList = []
        }
      }
    }
  },
  data() {
    return {
      jiaxiaoMonth:null,
      performanceListDialog:false,
      setDepartTimeDialog:false,
      setDepartTime:null,
      departBusinessId:null,
      // 表格相关
      tableLoading: true,
      dataList: [],
      pageSize: 20,
      perPageSize:10,
      pageNum: 1,
      perPageNum:1,
      total: 0,
      perTotal: 0,
      pageSizes: [20, 30, 50],
      perPageSizes: [10, 30, 50],
      tokenData: {
        token: "",
      },
      searchForm: {
        keyword: null,
        gradeId: null,
        status: null,
        area: null,
        businessType: null,
        departId: null,
        groupId: null,
        chooseShowMonth: [new Date(new Date().getFullYear(), 0, 1), new Date(new Date().getFullYear(), 11, 1)],
      },
      departList: [],
      searchGroupList: [],
      formGroupList: [],
      performanceList:[],
      teamTypeList: [
        {
          label: '组长',
          value: 1,
        },
        {
          label: '组员',
          value: 2,
        }
      ],
      statusList: [
        {
          label: '可用',
          value: 1,
        },
        {
          label: '已辞职',
          value: 2,
        }
      ],
      businessTypeList: [
        {
          label: 'KA',
          value: 1,
        },
        {
          label: 'BD',
          value: 2,
        }
      ],
      dialogFormVisible: false,
      form: {
        businessId: null,
        username: '',
        telephone: '',
        basicSalary: 0,
        performanceGoodsValue: 0,
        internalValue: '',
        gradeId: '',
        area: '',
        joinTime: null,
        password: null,
        businessType: 1,
        departId: null,
        groupId: null,
        teamType: 2,
        performanceTime: null,
        customValue: {},
      },
      formLabelWidth: '120px',
      dialogTitle: '新增',
      rules: {
        departId: {required: true, message: '请选择部门', trigger: 'change'},
        telephone: {required: true, message: '请输入手机号', trigger: 'blur'},
      },
      gradeList: [],
      areaList: [],
      openBusinessMsgStatus: false,
      openBusinessId: null,
      performanceTimeList: [],
      showAddUpdatePerformanceDialog: false,
      chooseBusinessAccountId: null,
      inputPerformancePrice: null,
      inputPerformanceBasicSalary: null,
      monthList: [],
      businessAssistantList: [],
      productSelectionUserList: [],
      productSelectionAssistantUserList: [],
      chooseRoleList: [],
      roleLoading: false,
      chooseRoleMap: {},
      customFormValue: {},
    };
  },
  activated() {
    this.tokenData.token = this.$store.state.token;
    this.getGroupList()
    this.getSysLabelList()
    this.getAllChooseRoleList()
    this.getPost()
  },
  mounted() {
    this.tokenData.token = this.$store.state.token
    this.$bus.$on('clearSearchParams', () => {
      this.searchForm = {
        keyword: null,
        gradeId: null,
        status: null,
        area: null,
        businessType: null,
        departId: null,
        groupId: null,
        chooseShowMonth: [new Date(new Date().getFullYear(), 0, 1), new Date(new Date().getFullYear(), 11, 1)],
      }
    })
  },
  methods: {
    getAllChooseRoleList() {
      const params = {
        token: this.$store.state.token,
      };
      APIAdmin.getAllCustomRoleList(params).then((res) => {
        if (res.key === 1000) {
          res = res.result;
          var list = res.list
          list.forEach(item => {
            this.chooseRoleMap[item.id] = []
            this.customFormValue[item.customName] = item.roleName
          })
          this.chooseRoleList = list
          const keys = Object.keys(this.chooseRoleMap);
          this.getChooseUserList(keys.join(","))
        }
      });
    },
    getChooseUserList(roleIds){
      const chooseParams = {
        token: this.$store.state.token,
        roleId: roleIds,
      };
      APIAdmin.getChooseAdminUserList(chooseParams).then((res) => {
        if (res.key === 1000) {
          res = res.result;
          var data = res.data
          const keys = Object.keys(this.chooseRoleMap);
          keys.forEach(s => {
            this.chooseRoleMap[s] = data[s]
          })
        }
      });
    },
    changeSelectionAssistantUser(val){
      let list = []
      this.productSelectionUserList.forEach(item => {
        if(item.userId == val){
          list = item.selectionAssistantList
        }
      })
      this.productSelectionAssistantUserList = list
    },
    getProductSelectionUserList() {
      const params = {
        token: this.$store.state.token,
      };
      APIUser.getSelectionUserList(params).then((res) => {
        if (res.key === 1000) {
          res = res.result;
          this.productSelectionUserList = res.list
        }
      });
    },
    getBusinessAssistantList() {
      const params = {
        token: this.$store.state.token,
        roleId: "59,60",
      };
      APIAdmin.adminUserList(params).then((res) => {
        if (res.key === 1000) {
          res = res.result;
          this.businessAssistantList = res.list
        }
      });
    },
    inputChangePerformancePrice(val){
      this.inputPerformancePrice = val
      var list = this.performanceTimeList
      list.forEach(item => {
        item.price = val
      })
      this.performanceTimeList = JSON.parse(JSON.stringify(list))
    },
    inputChangePerformancePriceCommit() {
      var list = this.performanceTimeList
      list.forEach(item => {
        item.price = this.inputPerformancePrice
      })
      this.performanceTimeList = JSON.parse(JSON.stringify(list))
    },
    inputChangePerformanceBasicSalary(val) {
      this.inputPerformanceBasicSalary = val
      var list = this.performanceTimeList
      list.forEach(item => {
        item.basicSalary = val
      })
      this.performanceTimeList = JSON.parse(JSON.stringify(list))
    },
    inputChangePerformanceBasicSalaryCommit() {
      if (this.inputPerformanceBasicSalary) {
        var list = this.performanceTimeList
        list.forEach(item => {
          item.basicSalary = this.inputPerformanceBasicSalary
        })
        this.performanceTimeList = JSON.parse(JSON.stringify(list))
      }
    },
    saveAddUpdatePerformance(){
      const params = {
        token: this.$store.state.token,
        businessId: this.chooseBusinessAccountId,
      }
      let timeList = []
      if (this.performanceTimeList && this.performanceTimeList.length > 0) {
        let addPerformanceTime = true
        let timeString = ''
        this.performanceTimeList.forEach(item => {
          if (item.time && (!item.price && item.price != 0) && (!item.basicSalary && item.basicSalary != 0)) {
            addPerformanceTime = false
            timeString = this.formatterTimeYYYYMM(item.time)
          }
          timeList.push({
            time: new Date(item.time).getTime(),
            price: item.price,
            basicSalary: item.basicSalary
          })
        })
        if (!addPerformanceTime) {
          this.$message({
            message: '请输入' + timeString + '的价格',
            type: 'error'
          });
          return
        }
      }
      if (timeList.length > 0) {
        params.performanceTimeList = JSON.stringify(timeList)
      }
      API.doAddPerformanceList(params).then((res) => {
        if (res.key === 1000) {
          this.$message({
            message: '添加成功',
            type: 'success'
          });
          this.perPageNum = 1
          this.perPageSize = 10
          this.selectPerformanceList()
          this.showAddUpdatePerformanceDialog = false
        }
      });
    },
    showAddUpdatePerformanceDialogClick() {
      this.form.performanceTime = null
      this.performanceTimeList = []
      this.inputPerformancePrice = null
      this.inputPerformanceBasicSalary = null
      this.showAddUpdatePerformanceDialog = true
    },
    handleShowAddUpdatePerformanceDialog(){
      this.showAddUpdatePerformanceDialog = false
    },
    delPerformanceTime(item, index){
      this.performanceTimeList.splice(index, 1)
      let chooseTimeIndex = null
      this.form.performanceTime.forEach((timeItem, timeIndex) => {
        if(timeItem == item.time){
          chooseTimeIndex = timeIndex
        }
      })
      if (chooseTimeIndex || chooseTimeIndex == 0){
        this.form.performanceTime.splice(chooseTimeIndex, 1)
      }
    },
    handleCloseDepartTimeDialog() {
      this.setDepartTimeDialog = false;
    },
    changeAreaList(val, listName) {
      const params = {
        token: this.$store.state.token,
        targetId: val
      }
      APISysLabel.selectAllGroup(params).then((res) => {
        if (res.key === 1000) {
          res = res.result;
          this[listName] = res.list
        }
      });
      if (listName === 'formGroupList' && this.dialogFormVisible) {
        this.form.groupId = ''
      }
      if (listName === 'searchGroupList') {
        this.searchForm.groupId = null
      }
    },
    handleCommand(e, row) {
      let that = this
      if (e == "handleViewClick") {
        this.handleViewClick(row)
      } else if (e == "handleClick") {
        this.handleClick(row)
      } else if (e == "handleClickResetPassword") {
        this.$confirm('确定重置密码吗？', '', {
          distinguishCancelAndClose: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        })
            .then(() => {
              that.handleClickResetPassword(row)
            })
            .catch(action => {
              this.$message({
                type: 'info',
                message: "取消成功"
              })
            });
      } else if (e == "handleClickResignation") {
        this.$confirm('确定设置辞职时间吗？', '', {
          distinguishCancelAndClose: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        })
            .then(() => {
              that.departBusinessId = row.id
              that.setDepartTime = row.departTime ?  new Date(row.departTime).getTime() : new Date().getTime()
              that.setDepartTimeDialog = true
            })
            .catch(action => {
              this.$message({
                type: 'info',
                message: "已取消修改"
              })
            });
      } else if (e == "handleClickDel") {
        this.$confirm('确定删除吗？', '', {
          distinguishCancelAndClose: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        })
            .then(() => {
              that.handleClickDel(row)
            })
            .catch(action => {
              this.$message({
                type: 'info',
                message: "取消成功"
              })
            });
      }else if (e == "handlePerformance") {
        this.handlePerformance(row)
      }
    },
    
    closeBusinessMsg() {
      this.openBusinessMsgStatus = false
      this.openBusinessId = null
    },
    handleViewClick(row) {
      this.openBusinessMsgStatus = true
      this.openBusinessId = row.id
    },
    selectPerformanceList(){
      const params = {
        token: this.$store.state.token,
        pageNum: this.perPageNum,
        pageSize: this.perPageSize,
        businessId: this.chooseBusinessAccountId,
      };
      API.selectPerformanceList(params).then((res) => {
        if (res.key === 1000) {
          res = res.result;
          this.perTotal = res.count;
          res.list.forEach(item => {
            if (item.chooseTime) {
              item.chooseTime = this.formatterTimeYYYYMMDD(item.chooseTime)
            }
          })
          this.performanceList = res.list;
          this.performanceListDialog = true;
        }
      });
    },
    handlePerformance(row) {
      this.chooseBusinessAccountId = row.id
      this.selectPerformanceList()
    },
    saveSetDepartTime() {
      const params = {
        token: this.$store.state.token,
        businessId: this.departBusinessId,
        status: 2,
        departTime : this.setDepartTime,
      };
      API.editBusinessStatus(params).then((res) => {
        if (res.key === 1000) {
          this.$message({
            message: '提交成功',
            type: 'success'
          });
          this.getPost();
          this.handleCloseDepartTimeDialog();
          this.departBusinessId = null;
        }
      });
    },
    handleClickResetPassword(row) {
      const params = {
        token: this.$store.state.token,
        businessId: row.id,
      };
      API.resetBusinessPassword(params).then((res) => {
        if (res.key === 1000) {
          this.$message({
            message: '重置成功',
            type: 'success'
          });
          this.getPost();
        }
      });
    },
    handleClickDel(row) {
      const params = {
        token: this.$store.state.token,
        businessId: row.id,
        status: 10,
      };
      API.editBusinessStatus(params).then((res) => {
        if (res.key === 1000) {
          this.getPost();
        }
      });
    },
    
    getSysLabelList() {
      const params = {
        token: this.$store.state.token,
        sysLabelIds: "3,11,32",
      };
      APISysLabel.getSysLabelValueManageList(params).then((res) => {
        if (res.key === 1000) {
          res = res.result;
          if (res.data) {
            this.areaList = res.data[3]
            this.gradeList = res.data[11]
            this.departList = res.data[32]
          }
        }
      });
    },
    getGroupList() {
      const params = {
        token: this.$store.state.token,
        targetId: ''
      };
      APISysLabel.selectAllGroup(params).then((res) => {
        if (res.key === 1000) {
          res = res.result;
          this.searchGroupList = res.list
        }
      });
    },
    backShow() {
      this.$emit('backShow')
    },
    handleClick(item) {
      let a = JSON.parse(JSON.stringify(item))
      if (a.customValue) {
        a.customValue = JSON.parse(a.customValue)
      } else {
        a.customValue = {}
        for (const customItem in this.customFormValue) {
          a.customValue[customItem] = null
          const matchedItem = this.chooseRoleList.find(roleItem => {
            return roleItem.customName === customItem;
          });
          if (matchedItem.multipleType == 1){
            a.customValue[customItem] = []
          }
        }
      }
      this.dialogTitle = '编辑'
      this.form = a
      this.form.businessId = a.id
      this.form.password = null
      this.changeAreaList(a.areaId, 'formGroupList')
      this.performanceTimeList = []
      this.inputPerformancePrice = null
      this.inputPerformanceBasicSalary = null
      this.getBusinessAssistantList()
      this.getProductSelectionUserList()
      this.dialogFormVisible = true
    },
    submit() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          const params = this.form
          this.form.area = this.areaList.find(item => item.id == this.form.areaId).sysValueName
          params.token = this.$store.state.token
          if (params.joinTime) {
            params.joinTime = new Date(params.joinTime).getTime()
          }
          if(params.performanceTime){
            params.performanceTime = params.performanceTime.toString()
          }
          let timeList = []
          if (this.performanceTimeList && this.performanceTimeList.length > 0){
            let addPerformanceTime = true
            let timeString = ''
            this.performanceTimeList.forEach(item => {
              if (item.time && (!item.price && item.price != 0) && (!item.basicSalary && item.basicSalary != 0)){
                addPerformanceTime = false
                timeString = this.formatterTimeYYYYMM(item.time)
              }
              timeList.push({
                time: new Date(item.time).getTime(),
                price: item.price,
                basicSalary: item.basicSalary
              })
            })
            if (!addPerformanceTime){
              this.$message({
                message: '请输入' + timeString + '的价格',
                type: 'error'
              });
              return
            }
          }
          if(timeList.length > 0){
            params.performanceTimeList = JSON.stringify(timeList)
          }
          // 处理角色选择人员
          if (params.customValue){
            params.customValue = JSON.stringify(params.customValue)
          }
          if (this.form.businessId) {
            params.businessId = this.form.businessId
            API.editBusiness(params).then((res) => {
              if (res.key === 1000) {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                });
                this.getPost()
                this.dialogFormVisible = false
              }
            });
          } else {
            API.addBusiness(params).then((res) => {
              if (res.key === 1000) {
                this.$message({
                  message: '添加成功',
                  type: 'success'
                });
                this.getPost()
                this.dialogFormVisible = false
              }
            });
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });

    },
    add() {
      let form = {
        businessId: null,
        username: '',
        telephone: '',
        basicSalary: 0,
        performanceGoodsValue: 0,
        internalValue: '',
        gradeId: '',
        area: '',
        joinTime: null,
        businessType: 1,
        departId: null,
        groupId: null,
        teamType: 2,
        customValue: {},
      }
      for (const customItem in this.customFormValue) {
        form.customValue[customItem] = null
        const matchedItem = this.chooseRoleList.find(roleItem => {
          return roleItem.customName === customItem;
        });
        if (matchedItem.multipleType == 1) {
          form.customValue[customItem] = []
        }
      }
      this.form = form
      this.changeAreaList('', 'formGroupList')
      this.performanceTimeList = []
      this.inputPerformancePrice = null
      this.getProductSelectionUserList()
      this.getBusinessAssistantList()
      this.dialogFormVisible = true
    },
    formatterTime(time) {
      return this.$moment(time).format("YYYY-MM-DD HH:mm:ss");
    },
    formatterTimeYYYYMMDD(time) {
      return this.$moment(time).format("YYYY-MM-DD");
    },
    formatterTimeYYYYMM(time) {
      return this.$moment(time).format("YYYY-MM");
    },
    // 全局初始化
    init() {
      // 搜索条件重置
      this.searchForm = {
        keyword: null,
        gradeId: null,
        status: null,
        area: null,
        businessType: null,
        departId: null,
        chooseShowMonth: [new Date(new Date().getFullYear(), 0, 1), new Date(new Date().getFullYear(), 11, 1)],
      };
      this.rePosts();
    },
    // 分页pageSize改变
    handleSizeChange(e) {
      this.pageSize = e;
      this.rePosts();
    },
    // 绩效分页pageSize改变
    handleSizeChangePer(e) {
      this.perPageSize = e;
      this.selectPerformanceList();
    },
    // 分页pageNum改变
    handleCurrentChange(e) {
      this.pageNum = e;
      this.getPost();
    },
    // 绩效分页pageNum改变
    handleCurrentChangePer(e) {
      this.perPageNum = e;
      this.selectPerformanceList();
    },
    // 重新请求
    rePosts() {
      this.pageNum = 1;
      this.dataList = [];
      this.getPost();
    },
    // 表格列表
    getPost() {
      this.tableLoading = true;
      const params = {
        token: this.$store.state.token,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      };
      if (this.searchForm.keyword) {
        params.keyword = this.searchForm.keyword
      }
      if (this.searchForm.gradeId) {
        params.gradeId = this.searchForm.gradeId
      }
      if (this.searchForm.status) {
        params.status = this.searchForm.status
      }
      if (this.searchForm.area) {
        params.areaId = this.searchForm.area
      }
      if (this.searchForm.businessType) {
        params.businessType = this.searchForm.businessType
      }
      if (this.searchForm.departId) {
        params.departId = this.searchForm.departId
      }
      if (this.searchForm.groupId) {
        params.groupId = this.searchForm.groupId
      }
      if (this.searchForm.chooseShowMonth && this.searchForm.chooseShowMonth.length > 0) {
        params.chooseShowStartMonth = new Date(this.searchForm.chooseShowMonth[0]).getTime()
        params.chooseShowEndMonth = new Date(this.searchForm.chooseShowMonth[1]).getTime()
      }
      API.getBusinessList(params).then((res) => {
        if (res.key === 1000) {
          res = res.result;
          let monthList = []
          res.data.forEach(item => {
            monthList.push({
              month: item[0] + "-" + (item[1] > 9 ? item[1] : ('0' + item[1])),
            })
          })
          this.total = res.count;
          this.monthList = monthList
          res.list.forEach(item => {
            if (item.createTime) {
              item.createDate = this.formatterTime(item.createTime)
            }
            if (item.joinTime) {
              item.joinDate = this.formatterTimeYYYYMMDD(item.joinTime)
            }
            if (item.departTime) {
              item.departTime = this.formatterTimeYYYYMMDD(item.departTime)
            }
            
          })
          this.dataList = res.list;
          this.tableLoading = false;
        }
      });
    },
  },
};
</script>

<style lang="sass">
.avatar-uploader
  .el-upload
    border: 1px dashed #d9d9d9
    border-radius: 6px
    cursor: pointer
    position: relative
    overflow: hidden

    &:hover
      border-color: #409eff

    .avatar-uploader-icon
      font-size: 28px
      color: #8c939d
      width: 100px
      height: 100px
      line-height: 100px !important
      text-align: center

    .avatar
      width: 100px
      height: 100px
      display: block
</style>
<style lang="sass" scoped>
.global-operation-list
  padding-left: 0

.global-select .global-select-btn
  background: #FFFFFF

.global-table-content
  padding: 0
  background-color: white
  width: 100%

.global-table-content-a
  margin: 0 auto
  width: 90%
  padding: 20px 0

.company-user-list
  //@include container
  .isStatus1
    width: 41px
    height: 21px
    background: #F1FFFC
    border-radius: 3px
    border: 1px solid #03C192
    font-size: 14px !important
    color: #03C192 !important
    line-height: 21px
    text-align: center

  .isStatus2
    width: 41px
    height: 21px
    background: #FFF2F2
    border-radius: 3px
    border: 1px solid #F46565
    font-size: 14px !important
    color: #F44141 !important
    line-height: 21px
    text-align: center

  .global-operation-left
    margin-right: 0

  ::v-deep .permission-dialog
    .el-dialog__body
      display: flex
      align-items: center
      flex-direction: column
      padding: 30px 60px

      .permission-dialog-tree
        width: 100%
        max-height: 450px
        overflow-y: auto
        overflow-x: hidden
        margin-bottom: 40px

  .global-table
    display: flex
    align-items: center
    justify-content: center
    flex-direction: column

    .list
      background: #FFFFFF
      box-shadow: 0px 0px 10px 0px rgba(93, 139, 198, 0.05)
      border-radius: 14px
      margin-bottom: 15px
      width: 100%
      display: flex
      align-items: center
      justify-content: space-between
      padding: 19px 24px

      .left
        display: flex
        align-items: center

        .img
          width: 90px
          height: 90px
          border-radius: 4px
          margin-right: 17px

        .nav
          .text1
            font-size: 20px
            font-weight: bold
            color: #222222
            line-height: 26px
            display: flex
            align-items: center
            justify-content: flex-start
            margin-bottom: 16px

            span
              height: 16px
              background: #FFF8ED
              border-radius: 11px
              border: 1px solid #FF9901
              font-size: 12px
              color: #FF9901
              line-height: 16px
              padding: 0 8px
              display: block
              text-align: center
              margin-left: 11px

          .text2
            display: flex
            align-items: center
            justify-content: flex-start
            margin-bottom: 25px

            i
              font-size: 20px
              color: #1861FD
              margin-right: 7px

            .text2_1
              font-size: 14px
              color: #222222
              line-height: 19px
              margin-right: 7px

            .text2_2
              margin-left: 5px
              font-size: 23px
              font-weight: bold
              color: #222222
              line-height: 29px
              margin-right: 3px

            .text2_3
              font-size: 14px
              color: #B5B5C3
              line-height: 19px

          .text3
            display: flex
            align-items: center

            i
              font-size: 14px
              color: #B5B5C3
              margin-right: 5px

            div
              font-size: 14px
              color: #B5B5C3
              line-height: 19px
              margin-right: 80px

      .right
//.permission-dialog-item
//  background: #f2f2f2

</style>
